/**
 * Copyright &copy; 2012-2016 <a href="https://www.kaaction.com">KAA</a> All rights reserved All rights reserved.
 */
package com.kaaction.modules.crab.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.kaaction.common.config.Global;
import com.kaaction.common.persistence.Page;
import com.kaaction.common.web.BaseController;
import com.kaaction.common.utils.StringUtils;
import com.kaaction.modules.crab.entity.Carrier;
import com.kaaction.modules.crab.service.CarrierService;

/**
 * 快递管理Controller
 * @author huanghaiming
 * @version 2017-07-21
 */
@Controller
@RequestMapping(value = "${adminPath}/crab/carrier")
public class CarrierController extends BaseController {

	@Autowired
	private CarrierService carrierService;
	
	@ModelAttribute
	public Carrier get(@RequestParam(required=false) String id) {
		Carrier entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = carrierService.get(id);
		}
		if (entity == null){
			entity = new Carrier();
		}
		return entity;
	}
	
	@RequiresPermissions("crab:carrier:view")
	@RequestMapping(value = {"list", ""})
	public String list(Carrier carrier, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Carrier> page = carrierService.findPage(new Page<Carrier>(request, response), carrier); 
		model.addAttribute("page", page);
		return "modules/crab/carrierList";
	}

	@RequiresPermissions("crab:carrier:form")
	@RequestMapping(value = "form")
	public String form(Carrier carrier, Model model) {
		model.addAttribute("carrier", carrier);
		return "modules/crab/carrierForm";
	}

	@RequiresPermissions("crab:carrier:save")
	@RequestMapping(value = "save")
	public String save(Carrier carrier, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, carrier)){
			return form(carrier, model);
		}
		int cnt = carrierService.getEqual(carrier);
		if(cnt>0){
			model.addAttribute("message", "该快递已存在");
			return form(carrier, model);
		}
		carrierService.save(carrier);
		addMessage(redirectAttributes, "保存快递管理成功");
		return "redirect:"+Global.getAdminPath()+"/crab/carrier/?repage";
	}
	
	@RequiresPermissions("crab:carrier:delete")
	@RequestMapping(value = "delete")
	public String delete(Carrier carrier, RedirectAttributes redirectAttributes) {
		carrierService.delete(carrier);
		addMessage(redirectAttributes, "删除快递管理成功");
		return "redirect:"+Global.getAdminPath()+"/crab/carrier/?repage";
	}

}